<?php
/**
 * 网络curl请求代理
 * User: Endy
 * Date: 2019/2/18
 */
namespace app\utils;

class CurlUtil
{

    /**
     * GET 请求获取数据
     * @param $url
     * @param int $time
     * @return bool|string
     * @throws \ErrorException
     */
    public static function getUrl($url, $time = 3)
    {
        $options = [
            'http' => [
                'method'  => "GET",
                'timeout' => $time,
            ]];
        try {
            $content = stream_context_create($options);
            $result  = file_get_contents($url, false, $content);
            if ($result)
                return $result;
        } catch (\ErrorException $e) {
            throw new \ErrorException($e->getMessage());
        }
        return false;
    }

    /**
     * curl上传文件
     * @param $url
     * @param $file
     * @param array $fields
     * @return mixed
     * @throws \ErrorException
     */
    public static function postFile($url, $file, $fields = [])
    {
        try {
            //$fields['media'] = '@' . $file;
            $fields['media'] = curl_file_create($file);
            return self::curl($url, $fields, true);
        } catch (\ErrorException $e) {
            throw new \ErrorException($e->getMessage());
        }
    }

    /**
     * curl上传JSON数据
     * @param $url
     * @param $data
     * @return mixed
     * @throws \ErrorException
     */
    public static function postJson($url, $data,$header)
    {
        try {
            $header = array_merge($header,['Content-Type: application/json; charset=utf-8',
                'Content-Length: ' . strlen($data)]);
            return self::curl($url, $data, true, $header);
        } catch (\ErrorException $e) {
            throw new \ErrorException($e->getMessage());
        }
    }

    /**
     * curl发送XML数据
     * @param $url
     * @param $data
     * @return mixed
     * @throws \ErrorException
     */
    public static function postXml($url, $data)
    {
        try {
            return self::curl($url, $data, true, ['Content-Type: text/xml']);
        } catch (\ErrorException $e) {
            throw new \ErrorException($e->getMessage());
        }
    }

    /**
     * 保存文件到本地
     * @param $url
     * @param $filePath
     * @return mixed
     * @throws \ErrorException
     */
    public static function saveFile($url, $filePath)
    {
        try {
            $content = self::curl($url);
            //保存图片到本地
            @file_put_contents($filePath, $content);
            return $filePath;
        } catch (\ErrorException $e) {
            throw new \ErrorException($e->getMessage());
        }
    }


    /**
     * curl调用
     * @param $url
     * @param bool $fields
     * @param bool $post
     * @param bool $head
     * @param int $time 连接超时时长默认5秒
     * @return mixed
     * @throws \ErrorException
     */
    public static function curl($url, $fields = false, $post = false, $head = false, int $time = 5)
    {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);        //返回获取的输出的文本流
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
        curl_setopt($ch, CURLOPT_TIMEOUT, $time);           //连接超时时间
        if ($post)
            curl_setopt($ch, CURLOPT_POST, 1);
        if ($fields)
            curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
        if ($head)
            curl_setopt($ch, CURLOPT_HTTPHEADER, $head);
        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \ErrorException($error);
        }
        curl_close($ch);
        return $result;
    }


    /**
     * 微信带证书请求
     * @param string $url 请求的地址
     * @param string $xml 提交的数据
     * @param string $certPre 证书appid路径
     * @param int $second
     * @return mixed
     * @throws \Exception
     */
    public static function postXmlSSLCurl($url, $xml, $certPre, $second = 10)
    {
        $dir = getcwd();
        $dir = dirname($dir) . '/extend/weChatCert/' . $certPre;
        $ch  = curl_init();
        //超时时间
        curl_setopt($ch, CURLOPT_TIMEOUT, $second);
        //这里设置代理，如果有的话
        //curl_setopt($ch,CURLOPT_PROXY, '8.8.8.8');
        //curl_setopt($ch,CURLOPT_PROXYPORT, 8080);
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
        //设置headerx
        curl_setopt($ch, CURLOPT_HEADER, FALSE);
        //要求结果为字符串且输出到屏幕上
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
        //设置证书
        //使用证书：cert 与 key 分别属于两个.pem文件
        //默认格式为PEM，可以注释c
        curl_setopt($ch, CURLOPT_SSLCERTTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLCERT, $dir . '/apiclient_cert.pem');
        //默认格式为PEM，可以注释
        curl_setopt($ch, CURLOPT_SSLKEYTYPE, 'PEM');
        curl_setopt($ch, CURLOPT_SSLKEY, $dir . '/apiclient_key.pem');
        //curl_setopt($ch, CURLOPT_CAINFO, $dir . '/rootca.pem');
        //post提交方式
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $xml);
        $data = curl_exec($ch);
        //返回结果
        if ($data) {
            curl_close($ch);
            return $data;
        } else {
            $error = curl_error($ch);
            curl_close($ch);
            throw new \Exception($error);
        }
    }
}